#include"MyString.h"
#include<string.h>
#include<stdio.h>
#include<stdlib.h>

void Print(MyString *obj);
int IsEqual(MyString *obj,MyString *obj2);
int IsContains(MyString *dest,MyString *src);
int Size(MyString *obj);
void RemoveString(MyString *dest,const char *str);
void InsertString(MyString *dest,const char *str,int index);
void FreeMySting(MyString *obj);

void Initialize(MyString *obj,const char *str)
{
    //strcpy(obj->string,str);
    obj->size=strlen(str);
    obj->string=(char *)malloc(sizeof(char)*(obj->size+1));
    if(obj->string==NULL)
    {
        printf("String malloc error!\n");
        return;
    }
    //obj->string=str;
    strcpy(obj->string,str);
    obj->print=Print;
    obj->iscontains=IsContains;
    obj->isequal=IsEqual;
    obj->removestring=RemoveString;
    obj->Strsize=Size;
    obj->insertstring=InsertString;
}

void Print(MyString *obj)
{
    printf("%s\n",obj->string);
}

int IsEqual(MyString *obj1,MyString *obj2)
{
    if(strcmp(obj1->string,obj2->string)==0)
    {
        return 1;
    }
    else
        return 0;
}

int IsContains(MyString *dest,MyString *src)
{
    if(strstr(dest->string,src->string))
    {
        return 1;
    }
    else
    {
        return 0;
    }
    
    return 0;
}

int Size(MyString *obj)
{
    return obj->size;
}

void RemoveString(MyString *dest, const char *str)
{
    char *RMstr=strstr(dest->string,str);
    if(RMstr)
    {
        char *destination = RMstr + strlen(str);
        while(*destination!='\0')
        {
            *RMstr=*destination;
            RMstr++;
            destination++;
        }
        *RMstr='\0';
    }
    else
    {
        return;
    }
}

void InsertString(MyString *dest, const char *str, int index)
{
    if(index<0||index>=dest->size)
    {
        return;
    }
    char *new_str=(char *)malloc(sizeof(char)*(dest->size+strlen(str)+1));
    if(new_str==NULL)
    {
        printf("new_str malloc error!\n");
        return;
    }
    strncpy(new_str,dest->string,index);
    strncpy(new_str+index,str,strlen(str));
    strcmp(new_str+index+strlen(str),dest->string+index);
    //dest->string=new_str;
    strcpy(dest->string,new_str);
    dest->size=strlen(dest->string);
    if(new_str!=NULL)
    {
        free(new_str);
        new_str=NULL;
    }
}
void FreeMySting(MyString *obj)
{
    if(obj->string!=NULL)
    {
        free(obj->string);
        obj->string=NULL;
    }
}

